<?php

namespace think\queue\job;

use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Message\AMQPMessage;
use think\queue\connector\Rabbitmq as RabbitmqQueue;
use think\queue\Job;

class Rabbitmq extends Job
{

    protected $channel;
    protected $message;
    protected $job;

    public function __construct(RabbitmqQueue $connection, AMQPChannel $channel, AMQPMessage $message, $queue)
    {
        $this->app = app();
        $this->connection = $connection;
        $this->channel = $channel;
        $this->message = $message;
        $this->job = $message->getBody();
        $this->queue = $queue;
    }

    /**
     * 获取任务ID
     * @return array|mixed|string
     */
    public function getJobId()
    {
        return $this->payload('id');
    }

    /**
     * 获取任务执行次数
     * @return int
     */
    public function attempts()
    {
        return $this->payload('attempts') + 1;
    }

    /**
     * 获取消息内容
     * @return string
     */
    public function getRawBody()
    {
        return $this->job;
    }

    /**
     * 删除任务
     * @return void
     */
    public function delete()
    {
        parent::delete();
        $this->channel->basic_ack($this->message->getDeliveryTag());
    }

    /**
     * 重新发布任务
     * @param int $delay
     * @return void
     */
    public function release($delay = 0)
    {
        parent::release($delay);
        $this->delete();
        $payload = $this->payload();
        $payload['attempts'] = $payload['attempts'] + 1;
        $options = [];
        if ($delay > 0) $options['delay'] = $delay;
        $this->connection->pushRaw(json_encode($payload), $this->queue, $options);
    }

}
